package com.collectplus.express.menu;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.webkit.JavascriptInterface;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.collectplus.express.BaseActivity;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppConfig;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.tools.JsCallback;

/**
 * 项目中用到的H5
 *
 * @author coffee<br>
 * 2015-7-27下午5:53:43
 */
public class WebViewActivity extends BaseActivity {

    protected WebView mWebView;
    private JsObject jsObject;
    private String title = "";
    private String url = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.webview);
        super.findViewById();

        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");
        setCommonTitle(title);
        if ("服务说明".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/serviceDescription.html";
        } else if ("法律条款".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/union_terms.html";
        } else if ("邮票说明".equals(title)) {
            title = "使用帮助";
            // url = AppConfig.getServerUrl() + "static/html/couponUseHelp.html";
            // url = "http://wx.shouhuobao.com/guor/direction.html";
            url = "https://mobile.shouhuobao.com/static/pages/direction.html";
        } else if ("用户使用条款".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/union_terms.html";
        } else if ("帮助中心".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/rock_help/index.html";
            //            url = "http://wx.shouhuobao.com/guor/help/help.html";
        } else if ("代收代寄服务说明".equals(title)) {
            // url = AppConfig.getServerUrl() + "static/html/useHelp.html";
            url = "http://wx.shouhuobao.com/guor/help/help.html";
        } else if ("如何获取投递袋".equals(title)) {
            // url = AppConfig.getServerUrl() + "static/html/useHelp.html";
            // url = "file:///android_asset/test_gotohome.html";
            // url = "http://wx.shouhuobao.com/guor/bag-tip.html";
            url = "https://www.wenjuan.com/s/n2u6fy/";
            jsObject = new JsObject();
        } else if ("服务范围".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/service_point.html";
            // url = "file:///android_asset/service_point.html";
        } else if ("如何使用快递柜".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/gegeBoxGuide.html";
        } else if ("开具发票".equals(title)) {
            url = "https://www.wenjuan.com/s/zauIzm/";
        } else if ("投递指南".equals(title)) {
            url = "http://wx.shouhuobao.com/guor/post-guide.html";
        } else if ("价格说明".equals(title)) {
            ReceiverBean receiverBean = AppCache.getParcelNew();
            if (receiverBean != null && receiverBean.getSender() != null && isNotEmpty(receiverBean.getSender().getCity())) {
                url = AppConfig.getServerUrl() + "static/html/price_usage.html?city=" + receiverBean.getSender().getCity();
            } else {
                url = AppConfig.getServerUrl() + "static/html/price_usage.html?city=" + AppCache.getCurrentCityName();
            }
        } else if ("服务保障".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/serviceAssurance.html";
        } else if ("驿站投递包裹指南".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/station_post_usage.html";
        } else if ("计价规则".equals(title)) {
            url = AppConfig.getServerUrl() + "static/html/price_guide.html";
        } else if ("邮票使用介绍".equals(title)) {
            url = AppConfig.getServerUrl() + "static/promo/landRocketStamps.html";
        }
        //
        initWebView(url);
        //
        if (jsObject != null) {
            mWebView.addJavascriptInterface(jsObject, "android");
            mWebView.addJavascriptInterface(jsObject, "nativeMethod");
        }
    }

    public class JsObject implements JsCallback {
        @JavascriptInterface
        public void gotoHome() {
            Intent data = new Intent();
            setResult(RESULT_OK, data);
            // 注意当前类的Activity方法被重写了
            WebViewActivity.super.finish();
        }

        @JavascriptInterface
        public void copyExpressCode(String code) {

        }

        @JavascriptInterface
        public void shareToWechat(String orderId) {

        }
    }

    @SuppressLint("SetJavaScriptEnabled")
    protected void initWebView(final String url) {
        mWebView = (WebView) findViewById(R.id.webview);
        // mWebView.setBackgroundColor(0); // 设置背景色
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);// 设置无缓存(防止访问静态file的时候出问题)
        mWebView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 拨打电话
                if (url != null && url.startsWith("tel:")) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url != null) {
                    String scheme = Uri.parse(url).getScheme();//还需要判断host
                    String pathPrefix = Uri.parse(url).getLastPathSegment();
                    if (TextUtils.equals("guoer", scheme)) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                        if ("appLogin".equals(pathPrefix)) {
                            startActivityForResult(intent, 101);
                        } else {
                            startActivity(intent);
                            finish();
                        }
                        return true;
                    }
                    return false;
                } else {
                    return super.shouldOverrideUrlLoading(view, url);
                }
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                cancelLoadingDialog();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                showLoadingDialog(null);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
            }
        });
        if (url != null) {
            mWebView.loadUrl(url);
        }
        if (title.equals("帮助中心") || title.equals("领取优惠券") || title.equals("计价规则") || "邮票使用介绍".equals(title)) {
            WebChromeClient wvcc = new WebChromeClient() {
                @Override
                public void onReceivedTitle(WebView view, String title) {
                    super.onReceivedTitle(view, title);
                    setCommonTitle(title);
                }
            };
            // 设置setWebChromeClient对象
            mWebView.setWebChromeClient(wvcc);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        //点击登录，跳转到登录界面，登录成功返回
        if (RESULT_OK == resultCode && requestCode == 101) {
            mWebView.loadUrl(url + AppCache.getUser().getPhone());
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

    @Override
    public void finish() {
        WebBackForwardList webBackForwardList = mWebView.copyBackForwardList();
        if (webBackForwardList != null && webBackForwardList.getSize() > 0) {
            if (webBackForwardList.getSize() > 1) {
                if (webBackForwardList.getItemAtIndex(webBackForwardList.getSize() - 2).getTitle().equals(webBackForwardList.getCurrentItem().getTitle())) {
                    super.finish();
                } else {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        super.finish();
                    }
                }
            } else {
                super.finish();
            }
        } else {
            super.finish();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
    }
}
